//
//  playerTableviewHeader.m
//  SoundPill
//
//  Created by 宋旭东 on 16/8/23.
//  Copyright © 2016年 宋旭东. All rights reserved.
//
#define NavigationBar_HEIGHT 44

#import "playerTableviewHeader.h"
#import "playerTableViewController.h"
#import "LoginViewController.h"
#import "AppDelegate.h"
#import "UIViewExt.h"
#import "AFNetworking.h"
#import "SDWebImageManager.h"
#import "Player_personButton.h"
#import "playRequestModel.h"
#import "UIImageView+WebCache.h"
#import "DownSheet.h"
#import "DownSheetModel.h"
#import "JCAlertView.h"
#import "AliPayModel.h"
static void *kStatusKVOKey = &kStatusKVOKey;
static void *kDurationKVOKey = &kDurationKVOKey;
static void *kBufferingRatioKVOKey = &kBufferingRatioKVOKey;
@interface playerTableviewHeader ()<DownSheetDelegate>
{
    int textNum;
    int commentNum;
    int temp;
    float lastTime;
    float CoordinateX;
    BOOL  firstTextIsZero;
    BOOL _isLabX;
    NSNumber *isDanmuPost;
    NSString *location;
    NSString *priceStr;
    UILabel *downloadSpeed;
    JCAlertView *_alert;
}
@property (strong, nonatomic) playRequestModel *playRequest;
@property (strong, nonatomic) NSString *attentionState;
@property (assign, nonatomic) BOOL isTouched;
@property (strong, nonatomic) NSString *idStr;
@property (strong, nonatomic) NSArray *shareArray;
@property (strong, nonatomic) UIImageView *likeImageView;
@property (strong, nonatomic) UIImageView *commentImageView;
@property (strong, nonatomic) UILabel *likeLable;
@property (strong, nonatomic) UILabel *commentLable;
@property (strong, nonatomic) UILabel *dragAudioTime;
@property (strong, nonatomic) UIButton *shareButton;
@property (strong, nonatomic) UIButton *payButton;
@end

@implementation playerTableviewHeader
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES;
        self.backgroundColor = [UIColor whiteColor];
        self.showImageArray = [[NSMutableArray alloc] init];
        self.waveArray = [[NSMutableArray alloc] init];
        self.textContent = [[NSMutableArray alloc] init];
        self.textTimeLine = [[NSMutableArray alloc] init];
        [self createUserSubviews];
        [self createWorkSubviews];
        [self createTagview];
        [self createOperationButtons];
        [self initShareMenu];
        self.dragAudioTime = [[UILabel alloc] initWithFrame:CGRectMake(self.width / 2 - 50, NavigationBar_HEIGHT + self.width / 2 - 25, 100, 50)];
        _dragAudioTime.textColor = [UIColor whiteColor];
        _dragAudioTime.font = [UIFont fontWithName:@"Arial" size:30];//[UIFont systemFontOfSize:30];
        _dragAudioTime.textAlignment = NSTextAlignmentCenter;
        _dragAudioTime.backgroundColor = [UIColor clearColor];
        [self addSubview:_dragAudioTime];
        _dragAudioTime.hidden = YES;
        downloadSpeed = [[UILabel alloc] initWithFrame:CGRectMake(15, self.bottom - 2 * NavigationBar_HEIGHT, 60, 20)];
        downloadSpeed.backgroundColor = [UIColor clearColor];
        downloadSpeed.font = [UIFont systemFontOfSize:10];
        downloadSpeed.layer.borderColor = [UIColor blackColor].CGColor;
        downloadSpeed.layer.borderWidth = 2;
        downloadSpeed.textAlignment = NSTextAlignmentCenter;
        [self addSubview:downloadSpeed];
    }
    return self;
}
- (void)initShareMenu
{
    DownSheetModel *Model_2 = [[DownSheetModel alloc]init];
    Model_2.icon = @"UMS_wechat_timeline_icon@2x.png";
    Model_2.icon_on = @"UMS_wechat_timeline_icon@2x.png";
    Model_2.title = @"朋友圈";
    DownSheetModel *Model_6 = [[DownSheetModel alloc]init];
    Model_6.icon = @"UMS_wechat_icon@2x.png";
    Model_6.icon_on = @"UMS_wechat_icon@2x.png";
    Model_6.title = @"微信好友";
    DownSheetModel *Model_9 = [[DownSheetModel alloc] init];
    Model_9.icon = @"UMS_sina_icon.png";
    Model_9.icon_on = @"UMS_sina_icon.png";
    Model_9.title = @"新浪微博";
    
    if ([WXApi isWXAppInstalled]) {
        self.shareArray = [NSArray arrayWithObjects:Model_2,Model_6,Model_9, nil];
    } else {
        self.shareArray = [NSArray arrayWithObjects:Model_9, nil];
    }
}
#pragma mark -
#pragma mark 刷新界面
- (void)reloadViews:(Player_ShowModel *)playModel
{
    
    if (playModel.liked.boolValue == 0) {
        self.isLove = [NSNumber numberWithBool:NO ];
    } else {
        self.isLove = [NSNumber numberWithBool:YES ];
    }
    _isLabX = playModel.LabX.boolValue;
    location = playModel.location;
    //    NSLog(@"%@", location);
    priceStr = playModel.price;
    if (playModel.goods.length > 0) {
        self.priceArray = [NSArray arrayWithArray:[playModel.goods componentsSeparatedByString:@","]];
    }
    self.isPrivate = playModel.is_private;
    textNum = 0;
    temp = 0;
    commentNum = 0;
    CoordinateX = [UIScreen mainScreen].bounds.size.width / 2;
    self.images = [[NSArray alloc] initWithArray:playModel.images];
    self.imageTimeline = [[NSArray alloc] initWithArray:playModel.timeline];
    self.text = [[NSArray alloc] initWithArray:playModel.texts];
    self.persons = [[NSArray alloc] initWithArray:playModel.persons];
    self.tags = [[NSArray alloc] initWithArray:playModel.tags];
    
    
    self.love_count = playModel.love_count;
    self.commentCount = playModel.comment_count;
    self.duration = playModel.duration;
    self.uid = [playModel.user valueForKey:@"uid"];
    self.idStr = playModel.id;
    self.attentionState = [playModel.user valueForKey:@"follow"];
    [self loadLikeCount:_love_count commentCount:_commentCount.stringValue];
    [self resetUserSubviewWithAvatar:[NSURL URLWithString:[playModel.user valueForKey:@"avatar"]] userName:[playModel.user valueForKey:@"username"] userSex:[playModel.user valueForKey:@"sex"] userOccupation:[playModel.user valueForKey:@"utype"] relationState:_attentionState];
    
    if (priceStr.intValue > 0 && priceStr.integerValue <= 9) {
        [_payButton setTitle:[NSString stringWithFormat:@"%@元",priceStr] forState: UIControlStateNormal];
        _payButton.hidden = NO;
    } else {
        if (priceStr.intValue == 0) {
            _payButton.hidden = YES;
        } else {
            [_payButton setTitle:@"支付" forState: UIControlStateNormal];
            _payButton.hidden = NO;
        }
    }

    if (downloadSpeed) {
        downloadSpeed.hidden = NO;
    }

    self.playRequest= [[playRequestModel alloc] init];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [_playRequest getWaveForm:self workID:_idStr];
        [_playRequest requestComment:self workID:_idStr];
    });

}
- (void)refresh
{
    lastTime = 0.0;
    [_tagView removeFromSuperview];
    [self createTagview];
    [_showImageArray removeAllObjects];
    [self loadImageWithCount:0];
    [_waveScroll removeFromSuperview];
    [self createWave];
    [_audiotime removeFromSuperview];
    [self createTimeLabel];
    _showImage.labelBackground.frame = CGRectZero;
    _showImage.showView.frame = CGRectZero;
    [_textContent removeAllObjects];
    [_textTimeLine removeAllObjects];
    [self showTextAndPerson];
    [_rolling removeFromSuperview];
    _rolling = nil;
    if (!_rolling) {
        self.rolling = [[danmuView alloc] initWithFrame:CGRectMake(0, NavigationBar_HEIGHT + 10, self.width, self.width)];
        [self addSubview:_rolling];
        isDanmuPost = [NSNumber numberWithBool:NO];
    } else {
        
    }
}
- (void)showTextAndPerson
{
    if (_text.count > 0) {
        for (NSDictionary *dic in _text) {
            NSString *timeline = [dic valueForKey:@"timeline"];
            if (timeline.intValue == 0) {
                firstTextIsZero = YES;
            }
            float textmaskX = [UIScreen mainScreen].bounds.size.width / 2 + (_waveScroll.contentSize.width - [UIScreen mainScreen].bounds.size.width)*timeline.floatValue;
            UIImageView *textmask = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Edit_text_mark"]];
            textmask.frame = CGRectMake(textmaskX, _prossesWave.frame.size.height / 2 - 7, 15, 15);
            [_prossesWave addSubview:textmask];
            [_textContent addObject:[dic valueForKey:@"content"]];
            [_textTimeLine addObject:timeline];
            [self addAnimation:textmask repeate:MAXFLOAT];
        }
    }
    if (_imageTimeline.count > 0) {
        for (NSString *timeline in _imageTimeline) {
            float textmaskX = [UIScreen mainScreen].bounds.size.width / 2 + (_waveScroll.contentSize.width - [UIScreen mainScreen].bounds.size.width)*timeline.floatValue;
            UIImageView *textmask = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Edit_character_mark"]];
            textmask.frame = CGRectMake(textmaskX, _prossesWave.frame.size.height / 2 + 5, 15, 15);
            [_prossesWave addSubview:textmask];
            [self addAnimation:textmask repeate:MAXFLOAT];
        }
    }
    if (_persons.count > 0) {
        for (int i = 0; i < _persons.count; i++) {
            NSDictionary *dic = _persons[i];
            NSString *personType = [self personType:[dic valueForKey:@"key"]];
            NSString *personName = [NSString stringWithFormat:@"%@ %@", personType, [dic valueForKey:@"name"]];
            CGSize size = [personName sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16], NSFontAttributeName, nil]];
            Player_personButton *personBtn = [[Player_personButton alloc] initWithFrame:CGRectMake(CoordinateX, _prossesWave.frame.size.height / 2 + 25, size.width+25, 20)];
            
            personBtn.personName.text = personName;
            [_prossesWave addSubview:personBtn];
            CoordinateX += size.width + 30;
        }
    }
    if (location && location.length > 0) {
    } else {
        location = @"保密";
    }
    NSString *locationStr = [NSString stringWithFormat:@"位置: %@", location];
    CGSize size = [locationStr sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14], NSFontAttributeName, nil]];
    UILabel *locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(CoordinateX, _prossesWave.frame.size.height / 2 + 25, size.width + 20, 20)];
    locationLabel.backgroundColor = [UIColor colorWithRed:0.596f green:0.600f blue:0.604f alpha:1.00f];
    locationLabel.text = locationStr;
    locationLabel.textColor = [UIColor whiteColor];
    locationLabel.font = [UIFont systemFontOfSize:14];
    locationLabel.textAlignment = NSTextAlignmentCenter;
    [_prossesWave addSubview:locationLabel];
    
    [self getWorkId:self.workID];
}
- (void)addAnimation:(UIImageView *)mask repeate:(CGFloat)repeate
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    // 动画选项设定
    animation.duration = 0.5; // 动画持续时间
    animation.repeatCount = repeate; // 重复次数
    animation.autoreverses = YES; // 动画结束时执行逆动画
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    // 缩放倍数
    animation.fromValue = [NSNumber numberWithFloat:1.0]; // 开始时的倍率
    animation.toValue = [NSNumber numberWithFloat:1.25]; // 结束时的倍率
    // 添加动画
    [mask.layer addAnimation:animation forKey:@"scale-layer"];
}
-(NSString *)personType:(NSNumber *)typeNum
{
    if (typeNum.intValue == 0) {
        return @"人声:";
    } else if (typeNum.intValue == 1) {
        return @"创作者:";
    } else if (typeNum.intValue == 2) {
        return @"图像:";
    } else if (typeNum.intValue == 3) {
        return @"吉他:";
    } else if (typeNum.intValue == 4) {
        return @"贝斯:";
    } else if (typeNum.intValue == 5) {
        return @"鼓:";
    } else if (typeNum.intValue == 6) {
        return @"键盘:";
    } else if (typeNum.intValue == 7) {
        return @"管乐器:";
    } else if (typeNum.intValue == 8) {
        return @"弦乐器";
    } else if (typeNum.intValue == 9) {
        return @"民族乐器";
    }
    return nil;
}
#pragma mark -
#pragma mark 创建界面
- (void)createUserSubviews
{
    self.userbackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, NavigationBar_HEIGHT + 10)];
    [self addSubview:_userbackgroundView];
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userInfoClick:)];
    [_userbackgroundView addGestureRecognizer:recognizer];
    
    self.userCoverView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, _userbackgroundView.height - 20 ,  _userbackgroundView.height - 20)];
    [self addSubview:_userCoverView];
    
    self.userNameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _userNameLabel.textColor = [UIColor blackColor];
    _userNameLabel.font = [UIFont boldSystemFontOfSize:16];
    [self addSubview:_userNameLabel];
    
    self.userSexLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _userSexLabel.textColor = [UIColor grayColor];
    _userSexLabel.font = [UIFont systemFontOfSize:12];
    [self addSubview:_userSexLabel];
    
    self.userOccupationLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _userOccupationLabel.textColor = [UIColor grayColor];
    _userOccupationLabel.font = [UIFont systemFontOfSize:12];
    [self addSubview:_userOccupationLabel];
    
    self.attentionButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_attentionButton addTarget:self action:@selector(changeUserAttention:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_attentionButton];
}

- (void)createTagview
{
    self.tagView = [[Player_TagView alloc] initWithFrame:CGRectMake(0, _userbackgroundView.bottom + 5, self.width, 37)];
    [self addSubview:_tagView];
    CGFloat lasty = [_tagView createTagView:self.tags];
    _tagView.frame = CGRectMake(0, _userbackgroundView.bottom, self.width, lasty);
}
- (void)createWorkSubviews
{
    self.showImage = [[Player_imageView alloc] initWithFrame:CGRectMake(0, _userbackgroundView.height, self.width, self.width)];
    _showImage.userInteractionEnabled = YES;
    [self addSubview:_showImage];
    
    self.playerControlButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playerControlButton.frame = CGRectMake(0, _userbackgroundView.height, self.width, self.width);
    
    _playerControlButton.tag = 0;
    [_playerControlButton addTarget:self action:@selector(_actionPlayPause:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_playerControlButton];
}
- (void)createWave
{
    self.waveScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, _showImage.top + _showImage.height - 80, self.width, 160)];
    _waveScroll.contentSize = CGSizeMake(self.width + 6 * _waveArray.count, 0);
    _waveScroll.backgroundColor = [UIColor clearColor];
    _waveScroll.delegate = self;
    _waveScroll.pagingEnabled = NO;
    _waveScroll.bounces = NO;
    _waveScroll.showsHorizontalScrollIndicator = NO;
    [self addSubview:_waveScroll];
    self.backgroundWave = [[Player_waveform alloc] initWithFrame:CGRectMake(0, 0, _waveScroll.contentSize.width, _waveScroll.bounds.size.height)];
    _backgroundWave.backgroundColor = [UIColor clearColor];
    _backgroundWave.waveArray = _waveArray;
    [_waveScroll addSubview:_backgroundWave];
    self.prossesWave = [[Player_preWaveform alloc] initWithFrame:CGRectMake(0, 0, _waveScroll.contentSize.width, _waveScroll.bounds.size.height)];
    _prossesWave.backgroundColor = [UIColor clearColor];
    _prossesWave.preWaveArray = _waveArray;
    [_waveScroll addSubview:_prossesWave];
}
- (void)createTimeLabel
{
    self.audiotime = [[UILabel alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width  - 125, _showImage.bottom + 5, 110, 20)];
    self.audiotime.backgroundColor = [UIColor clearColor];
    _audiotime.font = [UIFont systemFontOfSize:12];
    _audiotime.textColor = [UIColor blackColor];
    _audiotime.textAlignment = NSTextAlignmentCenter;
    _audiotime.text = @"00'' 00\" | 00'' 00\"";
    [self addSubview:_audiotime];
}
- (void)createOperationButtons
{
    self.likeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, self.bottom - NavigationBar_HEIGHT, 30, 30)];
    _likeImageView.image = [UIImage imageNamed:@"Play_love_no"];
    [self addSubview:_likeImageView];
    self.likeLable = [[UILabel alloc] initWithFrame:CGRectMake(_likeImageView.right, _likeImageView.top, 50, _likeImageView.height)];
    _likeLable.font = [UIFont systemFontOfSize:16];
//    _likeLable.text = @"88888";
    [self addSubview:_likeLable];
    _likeImageView.userInteractionEnabled = YES;
    _likeLable.userInteractionEnabled = YES;
    UITapGestureRecognizer *likeTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(likeImageviewClick:)];
    UITapGestureRecognizer *likelableTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(likeImageviewClick:)];
    [_likeLable addGestureRecognizer:likelableTapRecognizer];
    [_likeImageView addGestureRecognizer:likeTapRecognizer];
    
    
    self.commentImageView = [[UIImageView alloc] initWithFrame:CGRectMake(_likeLable.right + 15, _likeImageView.top, _likeImageView.width, _likeImageView.height)];
    _commentImageView.image = [UIImage imageNamed:@"Play_comment_black"];
    [self addSubview:_commentImageView];
    self.commentLable = [[UILabel alloc] initWithFrame:CGRectMake(_commentImageView.right, _commentImageView.top, 50, _commentImageView.height)];
    _commentLable.font = _likeLable.font;
    [self addSubview:_commentLable];
    _commentImageView.userInteractionEnabled = YES;
    _commentLable.userInteractionEnabled = YES;
    UITapGestureRecognizer *commentTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(commentButtonClick:)];
    UITapGestureRecognizer *commentlableTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(commentButtonClick:)];
    [_commentImageView addGestureRecognizer:commentTapRecognizer];
    [_commentLable addGestureRecognizer:commentlableTapRecognizer];

    
    self.shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_shareButton setImage:[UIImage imageNamed:@"play_sharemenu@3x"] forState:UIControlStateNormal];
    [_shareButton addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_shareButton];
    
    self.payButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_payButton setBackgroundColor:[UIColor blackColor]];
    if (priceStr != nil && priceStr.integerValue <= 9) {
        [_payButton setTitle:[NSString stringWithFormat:@"%@元",priceStr] forState: UIControlStateNormal];
        _payButton.hidden = NO;
    } else {
        if (priceStr == nil || priceStr.intValue == 0) {
            _payButton.hidden = YES;
        } else {
            [_payButton setTitle:@"支付" forState: UIControlStateNormal];
            _payButton.hidden = NO;
        }
    }
    [_payButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _payButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [_payButton addTarget:self action:@selector(payClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_payButton];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.bottom - 5, self.width, 5)];
    lineView.backgroundColor = [UIColor colorWithRed:0.961 green:0.961 blue:0.961 alpha:1.00];
    [self addSubview:lineView];
    
}
#pragma mark - 
#pragma mark ------------数据加载
#pragma mark 图片数据
- (void)loadImageWithCount:(int)count
{
    NSString *imageURL = _images[count];
    [[SDWebImageManager sharedManager] downloadWithURL:[NSURL URLWithString:imageURL] options:SDWebImageLowPriority progress:^(NSUInteger receivedSize, long long expectedSize) {
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) {
        
        if ( image != nil) {
            if (count == 0) {
                [_showImage setImage:image];
            }
            [_showImageArray addObject:image];
            if (count < _images.count - 1) {
                [self loadImageWithCount:count + 1];
            }
        } else {
            [self loadImageWithCount:count];
        }
    }];
}
- (void)resetUserSubviewWithAvatar:(NSURL *)avatarurl userName:(NSString *)userName userSex:(NSString *)userSex userOccupation:(NSString *)userOccupation relationState:(NSString *)relationState
{
    [self.userCoverView setImageWithURL:avatarurl placeholderImage:[UIImage imageNamed:@"default_head"]];
    CGSize nameSize = [self getSizeOfString:userName font:_userNameLabel.font];
    _userNameLabel.text = userName;
    _userNameLabel.frame = CGRectMake(_userCoverView.right + 5, _userCoverView.top, nameSize.width, _userCoverView.height / 2);
    switch (userSex.intValue) {
        case 0:
            userSex = @"外星人";
            break;
        case 1:
            userSex = @"女";
            break;
        case 2:
            userSex = @"男";
            break;
        default:
            break;
    }
    CGSize sexSize = [self getSizeOfString:userSex font:_userSexLabel.font];
    _userSexLabel.text = userSex;
    _userSexLabel.frame = CGRectMake(_userNameLabel.right + 10, _userNameLabel.top, sexSize.width, _userNameLabel.height);
    
    CGSize occupationSize = [self getSizeOfString:userOccupation font:_userOccupationLabel.font];
    _userOccupationLabel.text = userOccupation;
    _userOccupationLabel.frame = CGRectMake(_userNameLabel.left, _userNameLabel.bottom, occupationSize.width, _userNameLabel.height);
    if (relationState.intValue == 0) {
        [_attentionButton setImage:[UIImage imageNamed:@"player_Attention"] forState:UIControlStateNormal];
        [_attentionButton setTitle:nil forState: UIControlStateNormal];
        _attentionButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_attentionButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    } else {
        [_attentionButton setImage:nil forState:UIControlStateNormal];
        [_attentionButton setTitle:@"已关注" forState: UIControlStateNormal];
        _attentionButton.titleLabel.font = [UIFont systemFontOfSize:12];
        [_attentionButton setTitleColor:[UIColor colorWithRed:0.600f green:0.600f blue:0.600f alpha:1.00f] forState:UIControlStateNormal];
        _attentionButton.layer.borderColor = [[UIColor clearColor] CGColor];
        _attentionButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -25);
    }
    _attentionButton.frame = CGRectMake(0, 0, 1.3 * _userCoverView.width, 1.3 * 0.3 * _userCoverView.width);
    _attentionButton.center = CGPointMake(self.width - _attentionButton.width / 2 - 10, _userbackgroundView.height / 2);
    if ([_uid isEqualToString:[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"]]) {
        _attentionButton.hidden = YES;
    } else {
        _attentionButton.hidden = NO;
    }
}
- (CGSize)getSizeOfString:(NSString *)string font:(UIFont *)font
{
    CGRect rect = [string boundingRectWithSize:CGSizeMake((self.width - _userCoverView.width) , _userCoverView.height / 2) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading  |NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    CGSize size = rect.size;
    return size;
}
- (void)loadLikeCount:(NSString *)likeCount commentCount:(NSString *)commentCount
{
//    NSLog(@"%@",likeCount);
    _likeLable.text = likeCount;
    if (_isLove.boolValue == YES) {
        _likeImageView.image = [UIImage imageNamed:@"Play_love_yes"];
    } else {
        _likeImageView.image = [UIImage imageNamed:@"Play_love_no"];
    }
    _commentLable.text = commentCount;
    CGSize likeSize = [self getSizeOfString:likeCount font:_likeLable.font];
    CGSize commentSize = [self getSizeOfString:commentCount font:_commentLable.font];
    _likeLable.frame = CGRectMake(_likeLable.left, _likeLable.top, likeSize.width, _likeLable.height);
    _commentImageView.frame = CGRectMake(_likeLable.right + 20, _commentImageView.top, _commentImageView.width, _commentImageView.height);
    _commentLable.frame = CGRectMake(_commentImageView.right, _commentImageView.top, commentSize.width, _commentImageView.height);
    _shareButton.frame = CGRectMake(_commentLable.right + 20, _commentImageView.top, _commentImageView.width, _commentImageView.height);
    _payButton.frame = CGRectMake(self.width - 10 - 2 * _shareButton.width, _shareButton.top + 3, _shareButton.width * 2, _shareButton.height - 6);
}
#pragma mark -
#pragma mark ------------事件
#pragma mark 音频事件
- (void)stopAudioPlayer{
    if ([_streamer status] == DOUAudioStreamerPlaying) {
        [_streamer stop];
    }
}
- (void)getWorkId:(NSString *)workId{
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/work/%@/tmpfile", workId];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.track = [[Track alloc] init];
        self.tempFile = [responseObject valueForKey:@"tmpfile"];
        NSString *saveName = [[_tempFile stringByReplacingOccurrencesOfString:@"http://" withString:@""] stringByReplacingOccurrencesOfString:@"/" withString:@""];
        NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSLibraryDirectory , NSUserDomainMask , YES ) firstObject ];
        NSString *savePath = [cachPath stringByAppendingPathComponent:saveName];
        if ([[NSFileManager defaultManager] fileExistsAtPath:savePath]) {
            [_track setAudioFileURL:[NSURL fileURLWithPath:savePath]];
            downloadSpeed.hidden = YES;
        } else {
            [_track setAudioFileURL:[NSURL URLWithString:_tempFile]];
            if ([AppDelegate shareDelegate].isWiFi == YES) {
                //                    [self downloadFileWithOption:nil withInferface:_tempFile savedPath:savePath downloadSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                //
                //                    } downloadFailure:^(AFHTTPRequestOperation *operation, NSError *error) {
                //
                //                    } progress:^(float progress) {
                //
                //                    }];
            }
        }
        if (_timer) {
            [_timer setFireDate:[NSDate distantPast]];
        } else {
            self.timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(_timerAction:) userInfo:nil repeats:YES];
        }
        [self _resetStreamer];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == kStatusKVOKey) {
        [self performSelector:@selector(_updateStatus)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    }
    else if (context == kDurationKVOKey) {
        [self performSelector:@selector(_timerAction:)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    }
    else if (context == kBufferingRatioKVOKey) {
        [self performSelector:@selector(_updateBufferingStatus)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
- (void)_updateStatus
{
    switch ([_streamer status]) {
        case DOUAudioStreamerPlaying:
            [_playerControlButton setBackgroundImage:nil forState:UIControlStateNormal];
            _isTouched = NO;
            _dragAudioTime.hidden = YES;
            [_timer setFireDate:[NSDate distantPast]];
            [_rolling resumeAnimation];
            break;
        case DOUAudioStreamerPaused: {
            //        if ([_streamer bufferingRatio] >= 0.3) {
            CATransition *transition = [CATransition animation];
            transition.duration = 0.5f;
            transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
            transition.delegate = self;
            transition.type = kCATransitionFade;
            [_playerControlButton.layer addAnimation:transition forKey:nil];
            [_playerControlButton setBackgroundImage:[UIImage imageNamed:@"Play_playButton"] forState:UIControlStateNormal];
            [_timer setFireDate:[NSDate distantFuture]];
            [_rolling pauseAnimation];
        }
            break;
        case DOUAudioStreamerIdle:
            if (_playerControlButton.hidden == YES) {
                _playerControlButton.hidden = NO;
            }
            [_playerControlButton setBackgroundImage:[UIImage imageNamed:@"Play_playButton"] forState:UIControlStateNormal];
            [_timer setFireDate:[NSDate distantFuture]];
            _showImage.labelBackground.hidden = YES;
            textNum = 0;
            commentNum = 0;
            [_streamer setCurrentTime:0];
            
            break;
        case   DOUAudioStreamerFinished:
//            if (downloadSpeed.hidden == YES &&_streamer.currentTime > 0&& ![_commentView.comment isFirstResponder] && _shouldPlayNextWork == YES ) {
//                [self.navigationController showSGProgressWithDuration:10 andTintColor:self.navigationController.navigationBar.tintColor andTitle:@"准备播放下一首..." ];
//            }
            [_streamer stop];
            //
//            [_playRequest requestComment:self workID:_idStr];
            break;
        case DOUAudioStreamerBuffering:
            //            [_statusLabel setText:@"buffering"];
            break;
            
        case DOUAudioStreamerError:
            //            [_statusLabel setText:@"error"];
            break;
    }
}
- (void)_cancelStreamer
{
    if (_streamer != nil) {
        [_streamer removeObserver:self forKeyPath:@"status"];
        [_streamer removeObserver:self forKeyPath:@"duration"];
        [_streamer removeObserver:self forKeyPath:@"bufferingRatio"];
        [_streamer stop];
        _streamer = nil;
    }
}
- (void)_updateBufferingStatus
{
    //    [_miscLabel setText:[NSString stringWithFormat:@"Received %.2f/%.2f MB (%.2f %%), Speed %.2f MB/s", (double)[_streamer receivedLength] / 1024 / 1024, (double)[_streamer expectedLength] / 1024 / 1024, [_streamer bufferingRatio] * 100.0, (double)[_streamer downloadSpeed] / 1024 / 1024]];
    downloadSpeed.text = [NSString stringWithFormat:@"%.2f %%", [_streamer bufferingRatio] * 100.0];
    if ([_streamer bufferingRatio] >= 1.0) {
        downloadSpeed.hidden = YES;
        if (_streamer.status != DOUAudioStreamerPlaying && _streamer.currentTime <= 1) {
            [_streamer play];
        }
    }
    if ([_streamer bufferingRatio] < 0.3) {
        [_streamer pause];
        [_playerControlButton setBackgroundImage:[UIImage imageNamed:@"Play_loading"] forState:UIControlStateNormal];
        _playerControlButton.userInteractionEnabled = NO;
    } else {
        //        if ([AppDelegate shareDelegate].isPlayerVC.boolValue == YES) {
        _playerControlButton.userInteractionEnabled = YES;
        if (_streamer.status != DOUAudioStreamerPlaying && _streamer.currentTime <= 1) {
            [_streamer play];
        }
        //        }
    }
}
- (void)_resetStreamer
{
    [self _cancelStreamer];
    _streamer = [DOUAudioStreamer streamerWithAudioFile:_track];
    
    [_streamer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:kStatusKVOKey];
    [_streamer addObserver:self forKeyPath:@"duration" options:NSKeyValueObservingOptionNew context:kDurationKVOKey];
    [_streamer addObserver:self forKeyPath:@"bufferingRatio" options:NSKeyValueObservingOptionNew context:kBufferingRatioKVOKey];
    if (_timer) {
        [_timer setFireDate:[NSDate distantPast]];
    }
    [_streamer play];
}

- (void)_timerAction:(id)timer
{
    if ([_streamer duration] == 0.0) {
        _waveScroll.contentOffset = CGPointMake(0, 0);
        [_prossesWave getAudioPresses:0.00];
    } else {
        if (_streamer.currentTime > 2.0 && isDanmuPost.boolValue == NO) {
            for (Comment *comment in _commentArray) {
                [_rolling createDanmuItem:comment];
            }
            isDanmuPost = [NSNumber numberWithBool:YES];
        }
        float pres = _streamer.currentTime / self.duration.floatValue;
        [self playProsses:pres];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"mm'' ss\" "];
        NSDate*currentDate = [NSDate dateWithTimeIntervalSince1970:_streamer.currentTime];
        NSDate*durationDate = [NSDate dateWithTimeIntervalSince1970:self.duration.floatValue];
        NSString *currentDateStr = [formatter stringFromDate:currentDate];
        NSString *durationDateStr = [formatter stringFromDate:durationDate];
        _audiotime.text = [NSString stringWithFormat:@"%@ |  %@", currentDateStr, durationDateStr];
    }
}
#pragma mark 音频控制
- (void)_actionPlayPause:(id)sender
{
//    [self.navigationController stop];
    //    if (_streamer.currentTime >= 1.2) {
    if ([_streamer status] == DOUAudioStreamerPaused || [_streamer status] == DOUAudioStreamerFinished) {
        [_streamer play];
        //            [_timer setFireDate:[NSDate distantPast]];
    } else if ([_streamer status] == DOUAudioStreamerPlaying){
        [_streamer pause];
        
        //            [_timer setFireDate:[NSDate distantFuture]];
    } else if ([_streamer status] == DOUAudioStreamerIdle) {
        [self _resetStreamer];
    }
    //    }
//    if ([_commentView.comment isFirstResponder]) {
//        //        [_commentView.comment resignFirstResponder];
//        [[UIApplication sharedApplication].keyWindow endEditing:YES];
//        [UIView beginAnimations:@"anim" context:NULL];
//        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//        [UIView setAnimationBeginsFromCurrentState:YES];
//        [UIView setAnimationDuration:0.25];
//        //处理移动事件，将各视图设置最终要达到的状态
//        _commentView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 64 - 45, self.view.frame.size.width, 45);
//        [UIView commitAnimations];
//        //        [_commentView.comment resignFirstResponder];
//        [[UIApplication sharedApplication].keyWindow endEditing:YES];
//        _commentView.send.hidden = YES;
//    }
}
- (void)playProsses:(float)timer
{
    //NSLog(@"播放");
    if (timer <= 1) {
        CGPoint newOffset = _waveScroll.contentOffset;
        newOffset.x = (_waveScroll.contentSize.width - [UIScreen mainScreen].bounds.size.width) * timer;
        [UIView beginAnimations:@"scrollAnimation" context:nil];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:UIViewAnimationCurveLinear];
        _waveScroll.contentOffset = newOffset;
        [UIView commitAnimations];
        [_prossesWave getAudioPresses:timer];
        [_backgroundWave getAudioPresses:timer offset:_waveScroll.contentOffset.x + self.width / 2];
    }
    [self showTextInTextLabel:timer];
    [self changeImage:timer];
}
- (void)showTextInTextLabel:(float)time
{
    if ( time >= 0) {
        for (int i = textNum ; i < _textTimeLine.count; i++) {
            NSString *timeline = _textTimeLine[i];
            float timelineF = timeline.floatValue;
            if (timelineF <= time) {
                if (_showImage.labelBackground.hidden == YES) {
                    _showImage.labelBackground.hidden = NO;
                }
                [_showImage setLabelText:_textContent[i]];
                textNum = i;
            }
        }
    }
}
- (void)changeImage:(float)time
{
    for (int i = 0; i < _showImageArray.count; i++) {
        NSString *timeline = _imageTimeline[i];
        if (timeline.floatValue <= time) {
            CATransition *transition = [CATransition animation];
            transition.duration = 0.5f;
            transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
            transition.delegate = self;
            transition.type = kCATransitionFade;
            [_showImage.layer addAnimation:transition forKey:nil];
            _showImage.image = _showImageArray[i];
        }
    }
}
#pragma mark （ScrollView Delegate）
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"mm'' ss\" "];
    NSDate*currentDate = [NSDate dateWithTimeIntervalSince1970:_streamer.currentTime];
    NSDate*durationDate = [NSDate dateWithTimeIntervalSince1970:self.duration.floatValue];
    NSString *currentDateStr = [formatter stringFromDate:currentDate];
    NSString *durationDateStr = [formatter stringFromDate:durationDate];
    _audiotime.text = [NSString stringWithFormat:@"%@ |  %@", currentDateStr, durationDateStr];
    
    if (_isTouched == YES) {
        if (scrollView.contentOffset.x <= scrollView.contentSize.width) {
            float waveProgress = scrollView.contentOffset.x ;
            float waveLen = scrollView.contentSize.width - self.width;
            float vaule = waveProgress / waveLen;
            [_streamer setCurrentTime:self.duration.floatValue *vaule];
            textNum = 0;
            [self playProsses:vaule];
            _playerControlButton.hidden = YES;
            _dragAudioTime.hidden = NO;
            _dragAudioTime.text = [NSString stringWithFormat:@"%@", currentDateStr];
        } else {
        }
    }
    
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_streamer pause];
    self.isTouched = YES;
}
-(void)scrollViewWillBeginDecelerating: (UIScrollView *)scrollView{
    textNum = 0;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.3f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    transition.delegate = self;
    transition.type = kCATransitionFade;
    [_playerControlButton.layer addAnimation:transition forKey:nil];
    _playerControlButton.hidden = NO;
    _dragAudioTime.hidden = YES;
    _isTouched = NO;
    [_streamer play];
    //    [_timer setFireDate:[NSDate distantPast]];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    CATransition *transition = [CATransition animation];
    transition.duration = 0.3f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    transition.delegate = self;
    transition.type = kCATransitionFade;
    [_playerControlButton.layer addAnimation:transition forKey:nil];
    _playerControlButton.hidden = NO;
    _dragAudioTime.hidden = YES;
    if (decelerate == NO) {
        [_streamer play];
        //        [_timer setFireDate:[NSDate distantPast]];
    }
}
#pragma mark 用户事件
- (void)userInfoClick:(id)sender
{
    _userBlock();
}
- (void)changeUserAttention:(id)sender
{
    if ([_attentionState intValue]== 0) {
        if ([[NSUserDefaults standardUserDefaults] valueForKey:@"uid"] == nil) {
            //我的
            //提示请先登陆
            [JCAlertView showTwoButtonsWithTitle:@"未登录" Message:@"登录后才能继续操作" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"再看看" Click:^{
                
            } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"去登录" Click:^{
                [[AppDelegate shareDelegate] chooseRootViewController];
            }];
        } else {
            [self requestAttention];
            
        }
    }
}
- (void)requestAttention
{
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/follow", _uid];
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [session.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [session POST:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [netWorkManager stopMonitoring];
        //        NSLog(@"--------------数据请求成功---------------");
        [_attentionButton setImage:nil forState:UIControlStateNormal];
        [_attentionButton setTitle:@"已关注" forState: UIControlStateNormal];
        _attentionButton.titleLabel.font = [UIFont systemFontOfSize:12];
        [_attentionButton setTitleColor:[UIColor colorWithRed:0.600f green:0.600f blue:0.600f alpha:1.00f] forState:UIControlStateNormal];
        _attentionButton.layer.borderColor = [[UIColor clearColor] CGColor];
        _attentionButton.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -10);
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeAttenArray" object:self];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"error = %@", error);
    }];
}
- (void)likeImageviewClick:(id)sender
{
    playerTableViewController *player = (playerTableViewController *)self.nextResponder.nextResponder.nextResponder;
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"uid"]!=nil) {
        //取消赞发请求
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
        [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
        NSDictionary *data = [[NSDictionary alloc]init];
        if (self.isLove.boolValue == YES) {
            NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/work/%@/unlove",self.workID];
            [manager POST:str parameters:data progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                //                NSString *html = operation.responseString;
                //                NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dict = responseObject;
                if (responseObject) {
                    if([NSNumber numberWithBool:[[dict objectForKey:@"status"] boolValue]].boolValue == YES){
//                        NSLog(@"计算前%@",_love_count);
                        _love_count = [[NSNumber numberWithInt:_love_count.intValue - 1] stringValue];
//                        NSString *jianyihou = [NSString stringWithFormat:@"%d",self.love_count.intValue - 1];
//                        self.love_count = jianyihou;
                        //                        self.likeLable.text = jianyihou;
                        self.isLove = [NSNumber numberWithBool:NO];
                        _likeImageView.image = [UIImage imageNamed:@"Play_love_no"];
                        [self loadLikeCount:_love_count commentCount:_commentCount.stringValue];
                    }else{
                        //提示网络有问题
                    }
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
                NSInteger statusCode = response.statusCode;
                if (statusCode == 401) {
                    LoginViewController *login = [[LoginViewController alloc] init];
                    player.view.window.rootViewController = login;
                }
            }];
        }else{
            //点赞发请求
            NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/work/%@/love",self.workID];
            [manager POST:str parameters:data progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *dict=responseObject;
                if (responseObject) {
                    if([NSNumber numberWithBool:[[dict objectForKey:@"status"] boolValue]].boolValue == YES){
                        _love_count = [[NSNumber numberWithInt:_love_count.intValue + 1] stringValue];
//                        NSString *jiayihou = [NSString stringWithFormat:@"%d",self.love_count.intValue +1];
//                        self.love_count=jiayihou;
                        //                        self.likeLable.text = jiayihou;
                        self.isLove = [NSNumber numberWithBool:YES];
                        //点赞动画
                        CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
                        // 动画选项设定
                        animation.duration = 0.2; // 动画持续时间
                        animation.repeatCount = 1; // 重复次数
                        animation.autoreverses = YES; // 动画结束时执行逆动画
                        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
                        // 缩放倍数
                        animation.fromValue = [NSNumber numberWithFloat:1.0]; // 开始时的倍率
                        animation.toValue = [NSNumber numberWithFloat:1.2]; // 结束时的倍率
                        // 添加动画
                        [self.likeImageView.layer addAnimation:animation forKey:@"scale-layer"];
                        _likeImageView.image = [UIImage imageNamed:@"Play_love_yes"];
                        [self loadLikeCount:_love_count commentCount:_commentCount.stringValue];
                    }else{
                        //提示网络有问题
                    }
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
                NSInteger statusCode = response.statusCode;
                if (statusCode == 401) {
                    LoginViewController *login = [[LoginViewController alloc] init];
                    player.view.window.rootViewController = login;
                }
            }];
        }
    }else{
        [JCAlertView showTwoButtonsWithTitle:@"未登录" Message:@"登录后才能继续操作" ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"再看看" Click:^{
            
        } ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"去登录" Click:^{
            [self stopAudioPlayer];
            [self _cancelStreamer];
            [_timer invalidate];
            _timer = nil;
            [[AppDelegate shareDelegate] chooseRootViewController];
        }];
    }
}
- (void)commentButtonClick:(id)sender
{
    _commentBlock();
}
- (void)share
{
    if (_shareArray.count > 1) {
        DownSheet *sheet = [[DownSheet alloc]initWithlist:_shareArray height:0];
        sheet.delegate = self;
        [sheet showInViewController:nil];
    } else {
        playerTableViewController *player = (playerTableViewController *)self.nextResponder.nextResponder.nextResponder;
        [player shareToSina];
    }
        
}
- (void)didSelectIndex:(NSInteger)index
{
    playerTableViewController *player = (playerTableViewController *)self.nextResponder.nextResponder.nextResponder;
    if (_shareArray.count > 1) {
        switch (index) {
            case 0:
                [player shareToWXTimeline];
                break;
            case 1:
                [player shareToWXSession];
                break;
            case 2:
                [player shareToSina];
                break;
            default:
                break;
        }
    } else {
        
    }
}
- (void)payClick:(id)sender
{
    if (_isLabX == 0) {
        [self payAlertShow];
    } else {
        _payBlock(_workID, [_showImageArray firstObject],_tags,self.priceArray,priceStr,_love_count,_commentCount.stringValue);
    }
}
- (void)payAlertShow
{
    
    UIView *customView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width - 90, 270)];
    customView.backgroundColor = [UIColor whiteColor];
    if (_isLabX == 0) {
        customView.frame = CGRectMake(0, 0, self.frame.size.width - 90, 180);
    }
    UIButton *doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [doneBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    doneBtn.backgroundColor = [UIColor whiteColor];
    doneBtn.frame = CGRectMake(0,0, 25, 25);
    doneBtn.center = CGPointMake(20, 20);
    [customView addSubview:doneBtn];
    [doneBtn addTarget:self action:@selector(cancelPay:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 25, customView.frame.size.width, 270 / 6)];
    //    titleLabel.backgroundColor = [UIColor redColor];
    if (_isLabX == 1) {
        titleLabel.text = @"确认支付";
    } else {
        titleLabel.text = @"打 赏";
    }
    titleLabel.font = [UIFont boldSystemFontOfSize:21];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [customView addSubview:titleLabel];
    
    UILabel *deLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, titleLabel.frame.origin.y + titleLabel.frame.size.height, 210, titleLabel.frame.size.height * 2)];
    deLabel.center = CGPointMake(customView.center.x, deLabel.frame.origin.y + titleLabel.frame.size.height - 5);
    deLabel.textAlignment = NSTextAlignmentCenter;
    if (_isLabX == 1) {
        deLabel.text = @"请确认手机号码，验证码稍后将会发送至该号码，实体物品将会有客服联系你";
    } else {
        deLabel.frame = CGRectMake(0, titleLabel.frame.origin.y + titleLabel.frame.size.height - 15, customView.frame.size.width, titleLabel.frame.size.height * 1.5);
        deLabel.text = [NSString stringWithFormat:@"喜欢该作品，并支持%@\n 作者会知道是你的打赏",_payButton.titleLabel.text];
    }
    
    deLabel.lineBreakMode = NSLineBreakByWordWrapping;
    deLabel.numberOfLines = 0;
    [customView addSubview:deLabel];
    
    UIButton *cancelbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    if (_isLabX == 1) {
        [cancelbtn setTitle:@"购买" forState:UIControlStateNormal];
    }else {
        [cancelbtn setTitle:@"确认" forState:UIControlStateNormal];
    }
    cancelbtn.backgroundColor = [UIColor blackColor];
    cancelbtn.frame = CGRectMake(10, customView.frame.size.height - (270 / 5 - 10) - 10, customView.frame.size.width - 20, 270 / 5 - 10);
    [customView addSubview:cancelbtn];
    [cancelbtn addTarget:self action:@selector(donePay:) forControlEvents:UIControlEventTouchUpInside];
    
    
    _alert = [[JCAlertView alloc] initWithCustomView:customView dismissWhenTouchedBackground:NO];
    [_alert show];
}
- (void)cancelPay:(UIButton *)sender
{
//    if ([phoneNO isFirstResponder]) {
//        [phoneNO resignFirstResponder];
//    }
    [_alert dismissWithCompletion:nil];
}
- (void)donePay:(UIButton *)sender
{
//    [phoneNO resignFirstResponder];
    [_alert dismissWithCompletion:nil];
    playerTableViewController *player = (playerTableViewController *)self.nextResponder.nextResponder.nextResponder;
    AliPayModel *model = [[AliPayModel alloc] init];
    
//    NSString *price = [_payButton.titleLabel.text stringByReplacingOccurrencesOfString:@"元" withString:@""];
    //    NSLog(@"%@",price);
    [model pay:player.title price:priceStr body:player.title work_id:player.workID telNumber:nil];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
